﻿#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
using EGL = UnityEditor.EditorGUILayout;
using UEB = UnityEditor.EditorUserBuildSettings;

namespace UFrame
{
    public class BuildGameEditor : EditorWindow
    {
        public class BuildMacro
        {
            public string name;
            public bool selectValue;
        }

        public static bool isAbb = false;
        private static bool isInit = false;
        public static string defaultOutPath = string.Empty;
        public static string apkRequireName = string.Empty;
        public static List<BuildMacro> nameAry = new List<BuildMacro>();
        private bool isMacroTab;
        private Vector2 scrollPos = new Vector2(0, 0);
        private static string pathBuild = String.Empty;

        public static string copyAndroidStudioResPath = "";
        
        [DidReloadScripts]
        private static void InitInfo()
        {
            if (isInit)
            {
                return;
            }

            isInit = true;
            nameAry.Clear();
            TextAsset editorText = Resources.Load<TextAsset>("UFrameAssetEditor");
            if (editorText != null)
            {
                var lines = editorText.text.Split('\n');
                var defineMarco = StringTool.LineByKeyPair("UIDefineClass", lines);
                var marcoAry = defineMarco.Split(',');
                foreach (var item in marcoAry)
                {
                    nameAry.Add(new BuildMacro() {name = item});
                }
            }

            var t = UEB.selectedBuildTargetGroup;
            string defineList = PlayerSettings.GetScriptingDefineSymbolsForGroup(t);

            foreach (var item in nameAry)
            {
                item.selectValue = defineList.Contains(item.name + ";");
            }

            string dete = DateTime.Now.ToString("yyyy-M-d HH_mm_ss");
            BuildPlayerOptions b = new BuildPlayerOptions();
            string outPath = Application.dataPath + "/../";
            string pathBuild = outPath + PlayerSettings.productName + " " + dete;
            defaultOutPath = pathBuild;
            //Debug.Log("初始化");
        }

        [MenuItem("Plateface/BuildGame/SDKAdsBuildGameWindow", false, 1)]
        public static void BuildMenu()
        {
            var d = GetWindow(typeof(BuildGameEditor));
            InitInfo();
            d.titleContent = new GUIContent("打包窗口");
            d.Show();
        }


        public void OnGUI()
        {
            InitInfo();
            var targetGroup = UEB.selectedBuildTargetGroup;
            EGL.LabelField("输出路径:", defaultOutPath);
            apkRequireName = EGL.TextField("设置路径:", apkRequireName);
            if (targetGroup == BuildTargetGroup.Android)
                isAbb = EGL.Toggle("ABB格式", isAbb);

            isMacroTab = EGL.BeginToggleGroup("宏设置", isMacroTab);
            if (isMacroTab)
            {
                scrollPos = EGL.BeginScrollView(scrollPos, GUILayout.Height(100));
                int index = 0;
                int rowCol = 2;
                foreach (var item in nameAry)
                {
                    if (index % rowCol == 0)
                        EGL.BeginHorizontal();

                    bool oldValue = item.selectValue;
                    item.selectValue = EGL.Toggle(item.name, item.selectValue, GUI.skin.toggle);

                    if (oldValue != item.selectValue)
                    {
                        SetMacro();
                    }

                    index++;
                    if (index % rowCol == 0)
                    {
                        EGL.EndHorizontal();
                    }
                    else if (index == nameAry.Count)
                    {
                        EGL.EndHorizontal();
                    }
                }

                EGL.EndScrollView();
            }

            EGL.EndToggleGroup();

            if (GUILayout.Button("打包", GUILayout.Height(50)))
            {
                Build();
            }
        }

        public void SetMacro()
        {
            var t = EditorUserBuildSettings.selectedBuildTargetGroup;
            string defineList = PlayerSettings.GetScriptingDefineSymbolsForGroup(t);
            var list = defineList.Split(';');


            List<string> newMarco = new List<string>();
            List<string> ignoreMarco = new List<string>();

            foreach (var item in nameAry)
            {
                var hasStr = defineList.Contains(item.name + ";");
                if (item.selectValue == false && hasStr)
                {
                    ignoreMarco.Add(item.name);
                }
                else if (item.selectValue && hasStr)
                {
                }
                else if (item.selectValue == false && !hasStr)
                {
                    ignoreMarco.Add(item.name);
                }
                else
                {
                    newMarco.Add(item.name);
                }
            }

            StringBuilder sb = new StringBuilder();
            string temp = string.Empty;
            for (int i = 0; i < list.Length; i++)
            {
                if (ignoreMarco.Contains(list[i]))
                    continue;
                if (!temp.Contains(list[i] + ";"))
                {
                    sb.Append(list[i] + ";");
                    temp += list[i] + ";";
                }
            }

            for (int i = 0; i < newMarco.Count; i++)
            {
                if (!temp.Contains(newMarco[i] + ";"))
                {
                    sb.Append(newMarco[i] + ";");
                    temp += list[i] + ";";
                }
            }

            if (sb.ToString() != defineList)
            {
                PlayerSettings.SetScriptingDefineSymbolsForGroup(t, sb.ToString());
                Debug.Log("存储宏");
            }
        }


        public  void Build()
        {
            string textPath = string.Empty;
            pathBuild = GetBuildPath(out textPath);
            
         
            BuildPlayerOptions b = new BuildPlayerOptions();
            b.locationPathName = pathBuild;
            b.target = UEB.activeBuildTarget;
            b.targetGroup = UEB.selectedBuildTargetGroup;

            b.scenes = GetSceneAry();
            BuildPipeline.BuildPlayer(b);
            
           
        }

        [PostProcessBuild]
        public static void OnPostprocessBuild(BuildTarget buildTarget, string path)
        {
            if (string.IsNullOrEmpty(pathBuild))
                return;
            if (!File.Exists(pathBuild)){
                return;
            }
            
            if (buildTarget == BuildTarget.Android || buildTarget == BuildTarget.StandaloneWindows64)
            {
                //修复包名
                string textPath = String.Empty;
                string newPathBuild = GetBuildPath(out textPath);
                File.Move(pathBuild,newPathBuild);
                Debug.Log(pathBuild);
                pathBuild = String.Empty;
                BuildText(textPath, DateTime.Now.ToString("yyyy-M-d HH:mm:ss"));
                
            }
        }


        [PostProcessBuild]
        public static void OnPostprocessCopyAndroidStudioBuild(BuildTarget buildTarget, string path)
        {
            Debug.Log("结束打包: " + new DateTime().ToString());
            if (buildTarget == BuildTarget.Android && !string.IsNullOrEmpty(copyAndroidStudioResPath))
            {
                //D:\AndroidBuild\DrawGoalBuild\unityLibrary\src\main
                //D:\AndroidBuild\DrawGoal\unityLibrary\src\main
                Debug.Log("复制android");
                Debug.Log(path);
                string copyPath = path + @"\unityLibrary\src\main\";                            //打出包的路径
                string targetPath = copyAndroidStudioResPath + @"\unityLibrary\src\main\";      //拷贝到android工程路径
                
                //删除文件
                IOTool.DeleteAllFile(targetPath + "\\assets");
                IOTool.DeleteAllFile(targetPath + "\\jniLibs");

                IOTool.CopyDirectory(copyPath + "\\assets",targetPath + "\\assets", true);
                IOTool.CopyDirectory(copyPath + "\\jniLibs",targetPath + "\\jniLibs", true);
                
                
            }
        }

        public static string GetBuildPath(out string normalPath)
        {
            string dateStr1 = "yyyy-M-d HH_mm_ss";
            string dete = DateTime.Now.ToString(dateStr1);
            string outPath = Application.dataPath + "/../";
            string pathBuild = outPath + PlayerSettings.productName + " " + dete;
            if (!string.IsNullOrEmpty(apkRequireName))
            {
                pathBuild = apkRequireName;
            }

            string textPath = pathBuild + ".txt";
            normalPath = textPath;
            pathBuild = SetAndroidInfo(pathBuild);
            
            return pathBuild;
        }

        private static string SetAndroidInfo(string pathBuild)
        {
            if (UEB.activeBuildTarget != BuildTarget.Android)
                return pathBuild;

            if (isAbb)
            {
                UEB.buildAppBundle = true;
                pathBuild += ".abb";
            }
            else
            {
                pathBuild += ".apk";
                UEB.buildAppBundle = false;
            }

            return pathBuild;
        }

        public static void BuildText(string path, string time)
        {
            StringBuilder outSB = new StringBuilder();
            outSB.AppendLine("path(输出路径): " + path);
            outSB.AppendLine("selectedBuildTargetGroup(输出平台): " + UEB.selectedBuildTargetGroup);
            outSB.AppendLine("applicationIdentifier(包名): " + PlayerSettings.applicationIdentifier);
            outSB.AppendLine("Time(打包时间): " + time);
            outSB.AppendLine("isDevelopment(开发模式): " + UEB.development);
            outSB.AppendLine("allowDebugging(日志输出): " + UEB.allowDebugging);
            outSB.AppendLine("companyName(公司名): " + PlayerSettings.companyName);
            outSB.AppendLine("productName(产品名): " + PlayerSettings.productName);
            outSB.AppendLine("bundleVersion(版本号): " + PlayerSettings.bundleVersion);

            if (UEB.selectedBuildTargetGroup == BuildTargetGroup.Android)
            {
                outSB.AppendLine("targetArchitectures(编译架构): " + Enum.GetName(typeof(AndroidArchitecture),
                    PlayerSettings.Android.targetArchitectures));
                outSB.AppendLine("keystoreName(签名文件): " + PlayerSettings.Android.keystoreName);
                outSB.AppendLine("keystorePass(签名通道): " + PlayerSettings.Android.keystorePass);
                outSB.AppendLine("minSdkVersion(最小Android等级): " + PlayerSettings.Android.minSdkVersion);
                outSB.AppendLine("targetSdkVersion(目标Android等级): " + PlayerSettings.Android.targetSdkVersion);
            }

            outSB.AppendLine("ScriptingBackend(编译模式): " +
                             PlayerSettings.GetScriptingBackend(UEB.selectedBuildTargetGroup));

            var a = UEB.selectedBuildTargetGroup;
            outSB.AppendLine("Symbols(编译的宏): " + PlayerSettings.GetScriptingDefineSymbolsForGroup(a));

            string[] sceneAry = GetSceneAry();
            outSB.AppendLine("Scene(打包场景): \n" + string.Join("\n\t", sceneAry));

            File.WriteAllBytes(path, Encoding.UTF8.GetBytes(outSB.ToString()));
        }

        public static string[] GetSceneAry()
        {
            int len = EditorBuildSettings.scenes.Length;
            string[] sceneAry = new string[len];
            for (int i = 0; i < len; i++)
            {
                var a = EditorBuildSettings.scenes[i];
                sceneAry[i] = a.path;
            }

            return sceneAry;
        }
    }
}
#endif